package mobile;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.logging.Logger;

import main.Manager;

import comm.ReceivingThread;

/** Class that manages the whole connection with one given socket.
 * 
 * @author Bruno Zumba (03/10/2011)
 *
 */
public class MobileDevice extends Thread{
	private static Logger logger; //Debugging
	
	private static final int MOBILE_PORT = 9191;
	
	private Socket socket;
	private InputStream input;
	private OutputStream output;
	
	private String ip;
	
	private ReceivingThread receivingThread;
	
	public MobileDevice(String ip){
		logger = Logger.getLogger("framework.MobileDevice");
		
		this.ip = ip;
		
		try {
			socket = new Socket(ip, MOBILE_PORT);
		} catch (Exception e) {
			logger.warning("Couldn't connect to the mobile.");
			logger.warning(e.getMessage());
			e.printStackTrace();
		}
		
		System.out.println("IP dessa porra: "+this.ip);
	}
	
	public boolean iniciate(){
		System.out.println("Inicou o mob dev");
		try {
			input = socket.getInputStream();
			output = socket.getOutputStream();
		} catch (Exception e) {
			logger.warning("Couldn't get the I/O streams of the socket.");
			logger.warning(e.getMessage());
			e.printStackTrace();
			return false;
		}
		
		receivingThread = new ReceivingThread(this.socket, Manager.MOBILE);
		receivingThread.start();
		receivingThread.setRunning(true);

		
		
		return true;
	}
	
	public void killThread(){
		receivingThread.setRunning(false);
		receivingThread.clean();
	}
	
	/* Send the message through the socket */
	public void sendMessage(String str){
		byte[] buffer = new byte[1000];
		buffer = str.getBytes();
		
		System.out.println("Sending msg to mobile with ip: "+ip+"\n"+str);
		try {
			output.write(buffer, 0, str.length());
		} catch (Exception e) {
			logger.warning("Couldn't send message to mobile host: "+socket.getInetAddress().getHostAddress());
			logger.warning(e.getMessage());
			e.printStackTrace();
		}
	}
	
	public String getIp(){
		return this.ip;
	}
	
	public boolean isConnected(){
		if (!receivingThread.getRunning()){
			receivingThread.clean();
			return false;
		}
		return true;
	}
	

}
